/**
 * Keyboard driver
 * Copyright (c) 2013 Maris BECS. All rights reserved.
 */

#include "user_board.h"
#include "keyboard.h"

/**
 * \brief Check the status of the keyboard
 *
 * \param keybuffer a keyboard_event struct to store keyboard status
 */
void keyboard_get_key_state(struct keyboard_event *keybuffer)
{
	// Variable to hold the key mask
	static uint8_t key_state;

	if ((gpio_pin_is_low(MY_BUTTON3)) && !(key_state & KEYBOARD_ENTER_MASK)) {
		// ENTER key pressed
		key_state |= KEYBOARD_ENTER_MASK;
		keybuffer->keycode = KEYBOARD_ENTER;
		keybuffer->type = KEYBOARD_PRESS;

	} else if ((gpio_pin_is_high(MY_BUTTON3)) && (key_state & KEYBOARD_ENTER_MASK)) {
		// ENTER key released
		key_state &= ~KEYBOARD_ENTER_MASK;
		keybuffer->keycode = KEYBOARD_ENTER;
		keybuffer->type = KEYBOARD_RELEASE;

	} else if ((gpio_pin_is_low(MY_BUTTON4)) && !(key_state & KEYBOARD_UP_MASK)) {
		// UP key pressed
		key_state |= KEYBOARD_UP_MASK;
		keybuffer->keycode = KEYBOARD_UP;
		keybuffer->type = KEYBOARD_PRESS;

	} else if ((gpio_pin_is_high(MY_BUTTON4)) && (key_state & KEYBOARD_UP_MASK)) {
		// UP key released
		key_state &= ~KEYBOARD_UP_MASK;
		keybuffer->keycode = KEYBOARD_UP;
		keybuffer->type = KEYBOARD_RELEASE;

	} else if ((gpio_pin_is_low(MY_BUTTON5)) && !(key_state & KEYBOARD_DOWN_MASK)) {
		// DOWN key pressed
		key_state |= KEYBOARD_DOWN_MASK;
		keybuffer->keycode = KEYBOARD_DOWN;
		keybuffer->type = KEYBOARD_PRESS;

	} else if ((gpio_pin_is_high(MY_BUTTON5)) && (key_state & KEYBOARD_DOWN_MASK)) {
		// DOWN key released
		key_state &= ~KEYBOARD_DOWN_MASK;
		keybuffer->keycode = KEYBOARD_DOWN;
		keybuffer->type = KEYBOARD_RELEASE;

	} else if ((gpio_pin_is_low(MY_BUTTON1)) && !(key_state & KEYBOARD_BACK_MASK)) {
		// BACK key pressed
		key_state |= KEYBOARD_BACK_MASK;
		keybuffer->keycode = KEYBOARD_BACK;
		keybuffer->type = KEYBOARD_PRESS;

	} else if ((gpio_pin_is_high(MY_BUTTON1)) && (key_state & KEYBOARD_BACK_MASK)) {
		// BACK key released
		key_state &= ~KEYBOARD_BACK_MASK;
		keybuffer->keycode = KEYBOARD_BACK;
		keybuffer->type = KEYBOARD_RELEASE;

	} else {
		// No key actions detected
		keybuffer->keycode = KEYBOARD_NO_KEY;
		keybuffer->type = KEYBOARD_NO_EVENT;
	}
}
